/**
 * 波浪水球依赖文件
 */
var timer = null;
let canvas = getEleVal("waterPolo");
let ctx = canvas.getContext('2d');
var rangeValue = 0;
var nowRange = 0; //用于做一个临时的range

//画布属性
var mW = 120;
var mH = 120;
let lineWidth = 1;

//圆属性
var r = mH / 2; //圆心
var cR = r - 16 * lineWidth; //圆半径

//Sin 曲线属性
var sX = 0;
var sY = mH / 2;
var axisLength = mW; //轴长
let waveWidth = 0.1; //波浪宽度,数越小越宽    
let waveHeight = 6; //波浪高度,数越大越高
let speed = 0.05; //波浪速度，数越大速度越快
let xOffset = 0; //波浪x偏移量

ctx.lineWidth = lineWidth;

//画圈函数
let IsdrawCircled = false;
let drawCircle = function () {

	ctx.beginPath();
	ctx.strokeStyle = '#1080d0'; // 边框颜色
	ctx.arc(r, r, cR + 5, 0, 2 * Math.PI);
	ctx.stroke();
	ctx.beginPath();
	ctx.arc(r, r, cR, 0, 2 * Math.PI);
	ctx.clip();

}

//画sin 曲线函数
let drawSin = function (xOffset) {
	ctx.save();

	let points = []; //用于存放绘制Sin曲线的点

	ctx.beginPath();
	//在整个轴长上取点
	for (let x = sX; x < sX + axisLength; x += 20 / axisLength) {
		//此处坐标(x,y)的取点，依靠公式 “振幅高*sin(x*振幅宽 + 振幅偏移量)”
		let y = -Math.sin((sX + x) * waveWidth + xOffset);

		let dY = mH * (1 - nowRange / 100);

		points.push([x, dY + y * waveHeight]);
		ctx.lineTo(x, dY + y * waveHeight);
	}

	//封闭路径
	ctx.lineTo(axisLength, mH);
	ctx.lineTo(sX, mH);
	ctx.lineTo(points[0][0], points[0][1]);
	ctx.fillStyle = '#143D8B'; // 填充色
	ctx.fill();

	ctx.restore();
};

//写百分比文本函数
let drawText = function () {
	ctx.save();

	let size = 0.4 * cR;
	ctx.font = size + 'px Microsoft Yahei';
	ctx.textAlign = 'center';
	ctx.fillStyle = "rgba(06, 85, 128, 0.8)";
	ctx.fillText(~~nowRange + '%', r, r + size / 2);


};

let render = function () {
	canvas.width = mW;
	canvas.height = mH;
	ctx.clearRect(0, 0, mW, mH);
		drawCircle();
	if (nowRange <= rangeValue) {
		let tmp = 1;
		nowRange += tmp;
	}

	if (nowRange > rangeValue) {
		let tmp = 1;
		nowRange -= tmp;
	}

	drawSin(xOffset);
	drawText();

	xOffset += speed;
	timer = requestAnimationFrame(render);
}

render();

function updataWaterPolo(value) {
	this.rangeValue = value;
}
function updataHeight(value){
	this.mH = value;
	this.updataCircular();
	cancelAnimationFrame(timer); // 取消动画帧
	render();
}
function updataWidth(value){
	this.mW = value;
	this.updataCircular();
	cancelAnimationFrame(timer); // 取消动画帧
	render();
}
function updataCircular(){
	this.r = this.mH / 2;
	this.cR = this.r - 16 * lineWidth; //圆半径
	this.sY = this.mH / 2;
	this.axisLength = this.mW;
}